package com.qf.web;
import com.github.pagehelper.PageInfo;
import com.qf.bean.Dept;
import com.qf.bean.Employee;
import com.qf.bean.Role;
import com.qf.service.DeptService;
import com.qf.service.EmployeeService;
import com.qf.service.RoleService;
import com.qf.util.ExcelUtils;
import com.qf.util.enum1.EmployeeEnum;
import com.qf.util.enum1.PageEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.PortUnreachableException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/*
            敲得越多，钱越多！！！
            敲得越多，钱越多！！！
            敲得越多，钱越多！！！
*/
@Controller
public class EmployeeController {



    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;

    //批量删除
    @RequestMapping("/resource/demo2/deletebyids")
    public void deletes(int[] empid,HttpServletResponse response,String method){

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            if(method.equals("delete")){
                //此处的empid的数组为form表单提交后得到的多个name为empid的参数
                //删除被选中的id信息!!!
                //此句不能放在try的外面。因为这样不管走那个if语句，都会走这一句，这一句回把选中项的state属性置为0！！！
                int deletes = employeeService.deletes(empid);
                if(deletes>0){
                    out.print("<script>alert('删除成功');location.href='/subject_war_exploded/resource/demo2/getusers'</script>");
                }else {
                    out.print("<script>alert('删除失败');location.href='/subject_war_exploded/resource/demo2/getusers'</script>");
                }
            }else if(method.equals("daochu")) {
                //导出数据!!!
                //1、查询被选中的数据信息!!!
                List<Employee> findbyids = employeeService.findbyids(empid);
                //2、导出数据
                //2.1   为表起名字
                ExcelUtils.createFirst("用户信息");
//                把表的数据放进去
                ExcelUtils.createOthers(findbyids);
                //得到导出时候的时间,为下面的文件名做准备
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
                //设置流的导出地并且为.xls文件命名
                ExcelUtils.export(new FileOutputStream("f://"+(simpleDateFormat.format(new Date()))+".xls"));
                out.print("<script>alert('导出成功');location.href='/subject_war_exploded/resource/demo2/getusers'</script>");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除用户
    @RequestMapping("/resource/demo2/deletebyid")
    public void delete(int uid, HttpServletResponse response){
        //删除的方式：1、假删除==修改状态值    2、真删除   delete
        // 状态值   1表示未删除  0表示已删除
        int i = employeeService.deleteByPrimaryKey(uid, EmployeeEnum.DELETE.getIsline());
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            if(i>0){
                out.print("<script>alert('删除成功');location.href='/subject_war_exploded/resource/demo2/getusers'</script>");
            }else {
            out.print("<script>alert('删除失败');location.href='/subject_war_exploded/resource/demo2/getusers'</script>");
        }
    } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改
    @RequestMapping("/resource/demo2/updateEmp")
    public String update(Employee employee){
        int i = employeeService.updateByPrimaryKeySelective(employee);
        if(i>0){
            return "redirect:/resource/demo2/getusers";
        }
        return "redirect:/resource/demo2/findbyid?uid="+employee.getId();
    }

    //主键查询回显对象
    @RequestMapping("/resource/demo2/findbyid")
    public String findbyid(int uid,ModelMap map){
        //得到用户的信息
        Employee employee = employeeService.selectByPrimaryKey(uid);
        map.addAttribute("emp",employee);
        //查询所有部门的信息
        List<Dept> findalldepts = deptService.findalldepts();
        map.addAttribute("depts",findalldepts);
        System.out.println(employee.getRoleid());
        List<Role> roles = roleService.findbyDeptid(employee.getRoleid());
        System.out.println(roles);
        map.addAttribute("roles",roles);
        return "/resource/demo2/update";

    }


    //新增用户
    @RequestMapping("/resource/demo2/insertEmp")
    public String insert(Employee employee){
        //添加创建时间
        employee.setCreatedate(new Date());
        //1表示未删除，0表示已删除
        employee.setState(1);
        int insert = employeeService.insert(employee);
        if(insert>0){
            //新增成功
            return "redirect:/resource/demo2/getusers";
        }else {
            //新增失败
            return "redirect:/resource/demo2/getalldepts";
        }

    }


    //用户管理模块的查询列表,index表示页码值
    @RequestMapping("/resource/demo2/getusers")
//    给index一个默认值为String的1，因为这里只能给String类型的
    public String getall(@RequestParam(defaultValue = "1") int index, ModelMap map,String username,String rolename,String deptname){
        PageInfo<Employee> getall = employeeService.getall(index, PageEnum.pagesize.getSize(),username,rolename,deptname);
        map.addAttribute("pi",getall);
        map.addAttribute("uname",username);
        map.addAttribute("rname",rolename);
        map.addAttribute("dname",deptname);
        return "resource/demo2/list";
    }



    //登录
 //===============================================第一============================
    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session){
        Employee login = employeeService.login(username, password);
        System.out.println(login);
        if(login==null){
            return "login";
        }
        //将登陆成功的消息保存到session中
        session.setAttribute("user",login);
        //用重定向来跳转页面可以让用户看到跳了，而不是先去servlet再去跳，不让用户看到controler层
        //return "index";
        System.out.println("1");
        return "redirect:/index.jsp";
    }

    //退出(意为但钱用户信息不在，想要再次看到需要再次登录)
    @RequestMapping("/loginout")
    public String loginout(HttpSession session){
        //清除session
        session.invalidate();
        return "redirect:login.jsp";
    }

    //===============================================第一============================


}
